/**
 * Created by chengke on 2018/2/28.
 */

let iconv = require('iconv-lite');
let FutuHttpClient = require('@futu/httpclient');
let FutuHttpRequest = FutuHttpClient.FutuHttpRequest;
let OperationRecord = require('../models/OperationRecord');
let Adgroup = require('../models/Adgroup');

module.exports = OperationRecordService;

const BASE_API_URL = 'https://api.baidu.com/json/sms/service/ToolkitService/';
const API_GET_OPERATIONRECORD = 'getOperationRecord';

const OPERATIONRECORD_ATTRS = [
    'optType',
    'newValue',
    'optLevel',
    'userId',
    'optContent',
    'oldValue',
    'planId',
    'optObj',
    'unitId',
    'optTime'
];

/**
 * OperationRecordService
 *
 * @constructor
 * @param {String} username 用户名
 * @param {String} password 密码
 * @param {String} token API 令牌
 * @param {Object} options 扩展参数
 */
function OperationRecordService(username, password, token, options = {}) {
    this.username = username;
    this.password = password;
    this.token = token;
    this.options = options;
    this.commonHeader = {
        'username': this.username,
        'password': this.password,
        'token': this.token
    };
}

OperationRecordService.prototype.getOperationRecord = async function (startDate, endDate) {
    let result = await this._requestSemAPI(BASE_API_URL + API_GET_OPERATIONRECORD, {
        'startDate' : startDate,
        'endDate' : endDate,
        'optLevel': 5,
    });
    console.log(JSON.stringify(result, null, 2));
    if (result.header && result.header.status === 0) {
        return result.body.data;
    } else {
        return '';
    }
};

OperationRecordService.prototype.syncOperationRecord = async function (startDate, endDate) {
    let words = await this.getOperationRecord(startDate, endDate);
    console.log(words.length);
    return words.map(async function (item) {
        // item.pcScale = JSON.stringify(item.pcScale);
        // item.mobileScale = JSON.stringify(item.mobileScale);
        let word = await OperationRecord.findOne({
            where: {opt_time: item.optTime, user_id: item.userId}
        });
        let result;
        if (word) {
            result = word.update(item);
        } else {
            result = await OperationRecord.create(item);
        }
        console.log(result);
    });

};

OperationRecordService.prototype._requestSemAPI = async function (url, body) {
    let client = await FutuHttpClient.getInstanceByEndpoint();
    let request = new FutuHttpRequest(url, {}, {});
    request.setIsJson(true);
    request.setData({
        'header': this.commonHeader,
        'body': body
    });
    let response = await client.request('post', request);
    if (response.httpStatusCode !== 200) {
        throw new Error('request ' + url + 'failed: ' + response.message);
    }
    return JSON.parse(response.data || '{}');
};

OperationRecordService.timeout = function (ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
};
